package com.supor.aiot.common.push;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;

import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.SystemUtils;
import com.supor.aiot.common.R;

import androidx.core.app.NotificationCompat;

import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
import static android.content.Intent.FLAG_INCLUDE_STOPPED_PACKAGES;

public class NotificationHelper extends ContextWrapper {
    private NotificationManager mManager;
    private static final String CHANNEL_ID = "cookingChannel";
    private static final String CHANNEL_NAME = "小C PUSH";

    public NotificationHelper(Context context) {
        super(context);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            createNotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
        }
    }

    @TargetApi(Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        channel.setLightColor(Color.GRAY);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
        getManager().createNotificationChannel(channel);
    }

    private Notification getNotification(String title, String body) {
        Notification notification;
        boolean isAppAlive = true;
        PendingIntent pendingIntent;
        if(SystemUtils.isAppAlive(this, "com.supor.aiot")){
            //如果存活的话，就直接启动MessageCategoryActivity，但要考虑一种情况，就是app的进程虽然仍然在
            //但Task栈已经空了，比如用户点击Back键退出应用，但进程还没有被系统回收，如果直接启动
            //MessageCategoryActivity,再按Back键就不会返回HomeActivity了。所以在启动
            //MessageCategoryActivity前，要先启动HomeActivity。
            Logc.i("the app process is alive");
            //            Intent mainIntent = new Intent(context, HomeActivity.class);
            //将HomeActivity的launchMode设置成SingleTask, 或者在下面flag中加上Intent.FLAG_CLEAR_TOP,
            //如果Task栈中有HomeActivity的实例，就会把它移到栈顶，把在它之上的Activity都清理出栈，
            //如果Task栈不存在HomeActivity实例，则在栈顶创建
            //            mainIntent.setFlags(FLAG_ACTIVITY_NEW_TASK);

            ComponentName component = new ComponentName(this.getPackageName(), NotificationActivity.class.getName());
            Intent intent = new Intent();
            intent.putExtra("title", title);
            intent.putExtra("body", body);
            intent.setComponent(component);
            intent.addFlags(FLAG_INCLUDE_STOPPED_PACKAGES);
            intent.addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TOP);
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        }else {
            //如果app进程已经被杀死，先重新启动app，将MessageCategoryActivity的启动参数传入Intent中，参数经过
            //MainActivity传入HomeActivity，此时app的初始化已经完成，在HomeActivity中就可以根据传入参数跳转到MessageCategoryActivity中去了
            Logc.i("the app process is dead");
            isAppAlive = false;
            Intent launchIntent = new Intent()/*context.getPackageManager().getLaunchIntentForPackage("com.szsbay.zjk")*/;
            launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            //            launchIntent.setPackage("com.szsbay.zjk");
            launchIntent.setComponent(new ComponentName("com.supor.aiot", "com.supor.aiot.SuporMainActivity"));
            launchIntent.setAction(Intent.ACTION_MAIN);
            launchIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            launchIntent.putExtra("title", title);
            launchIntent.putExtra("body", body);
            pendingIntent = PendingIntent.getActivity(this, 0, launchIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notification = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setContentIntent(pendingIntent)
                    .setWhen(System.currentTimeMillis())
                    .setChannelId(CHANNEL_ID)
                    .setSmallIcon(getApplicationContext().getApplicationInfo().icon)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launch_logo))
                    .setAutoCancel(true)
                    .build();
        }else {
            notification = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setContentIntent(pendingIntent)
                    .setWhen(System.currentTimeMillis())
                    .setSmallIcon(getApplicationContext().getApplicationInfo().icon)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launch_logo))
                    .setAutoCancel(true)
                    .build();
        }
        return notification;
    }

    public void notify(String title, String body) {
        getManager().notify(1, getNotification(title, body));
    }

    private NotificationManager getManager() {
        if (mManager == null) {
            mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        }
        return mManager;
    }
}
